<script setup lang="ts">
  import { onMounted, reactive, ref } from 'vue';
  import useLoading from '@/hooks/loading';
  import { selectPageLoginLog, statisLoginLog } from '@/api/loginlog';
  import { PaginationProps, TableColumnData } from '@arco-design/web-vue';
  import { SeriesOption } from 'echarts';

  const { loading, setLoading } = useLoading(true);
  const params = ref({
    pageNo: 1,
    pageSize: 10,
    username: '',
  });
  const loginLogList = ref([]);
  const pagination = reactive<PaginationProps>({
    showTotal: true,
    showPageSize: true,
    pageSizeOptions: [5, 10, 50, 100],
  });
  const option = ref({
    title: {
      text: '一周日志统计',
    },
    tooltip: {
      trigger: 'axis',
      axisPointer: {
        type: 'shadow',
      },
    },
    grid: {
      left: '3%',
      right: '4%',
      bottom: '3%',
      containLabel: true,
    },
    xAxis: [
      {
        type: 'category',
        data: (function () {
          const dates: string[] = [];
          for (let i = 6; i >= 0; i -= 1) {
            const date = new Date(new Date());
            date.setDate(new Date().getDate() - i);
            dates.push(date.toISOString().split('T')[0]);
          }
          return dates;
        })(),
        axisTick: {
          alignWithLabel: true,
        },
      },
    ],
    yAxis: [
      {
        type: 'value',
      },
    ],
    series: [
      {
        name: '登录次数',
        type: 'bar',
        barWidth: '60%',
        itemStyle: {
          color: '#165DFF',
        },
        data: [],
      },
    ],
  });
  // 信息列表
  const columns: TableColumnData[] = [
    {
      title: '用户名',
      dataIndex: 'username',
      align: 'center',
      tooltip: true,
      ellipsis: true, // 超出内容显示省略号
    },
    {
      title: '状态',
      dataIndex: 'status',
      align: 'center',
      tooltip: true,
      ellipsis: true, // 超出内容显示省略号
      slotName: 'status',
    },
    {
      title: 'IP地址',
      dataIndex: 'ip',
      align: 'center',
      tooltip: true,
      ellipsis: true, // 超出内容显示省略号
    },
    {
      title: '浏览器信息',
      dataIndex: 'userAgent',
      align: 'center',
      tooltip: true,
      ellipsis: true,
    },
    {
      title: '登录时间',
      dataIndex: 'timestamp',
      align: 'center',
    },
    {
      title: '操作',
      align: 'center',
      slotName: 'operation',
      width: 250,
    },
  ];
  const getLoginLogList = async () => {
    setLoading(true);
    try {
      const result = await selectPageLoginLog(params.value);
      loginLogList.value = result.data.list;
      pagination.total = result.data.total;
      pagination.current = params.value.pageNo;
      pagination.pageSize = params.value.pageSize;
    } finally {
      setLoading(false);
    }
  };
  const getStatisLoginLog = async () => {
    const result = await statisLoginLog();
    if (option.value.series) {
      (option.value.series as SeriesOption[])[0].data = result.data.count;
    }
  };
  getLoginLogList();
  onMounted(() => {
    getStatisLoginLog();
  });
  // 查询
  const handleSearch = () => {
    params.value.pageNo = 1;
    getLoginLogList();
  };
  // 重置
  const handleReset = () => {
    params.value.pageNo = 1;
    params.value.username = '';
    getLoginLogList();
  };
  // 切换页面
  const handlePageNoChange = (pageNo: number) => {
    params.value.pageNo = pageNo;
    getLoginLogList();
  };
  // 变更页数数量
  const handlePageSizeChange = (pageSize: number) => {
    params.value.pageSize = pageSize;
    getLoginLogList();
  };
  // 添加删除方法
  const handleDelete = async (id: number) => {};
</script>

<template>
  <a-row style="margin-bottom: 6px">
    <a-col :span="24">
      <Chart :option="option" height="300px" />
    </a-col>
  </a-row>
  <a-divider style="margin-top: 10px; margin-bottom: 16px" />
  <a-row>
    <a-col :flex="1">
      <a-form
        :model="params"
        label-align="left"
        :label-col-props="{ span: 6 }"
        layout="inline"
        :wrapper-col-props="{ span: 18 }"
      >
        <a-form-item field="username" label="用户名：">
          <a-input v-model="params.username" placeholder="请输入用户名" />
        </a-form-item>
        <a-form-item>
          <a-space>
            <a-button
              v-permission="'log:loginlog:list'"
              type="primary"
              @click="handleSearch"
            >
              <template #icon>
                <icon-search />
              </template>
              {{ $t('searchTable.form.search') }}
            </a-button>
            <a-button type="primary" @click="handleReset">
              <template #icon>
                <icon-refresh />
              </template>
              {{ $t('searchTable.form.reset') }}
            </a-button>
          </a-space>
        </a-form-item>
      </a-form>
    </a-col>
  </a-row>
  <a-divider style="margin-top: 8px; margin-bottom: 16px" />
  <a-row style="flex: 1">
    <a-col :span="24" style="height: 100%">
      <a-table
        row-key="id"
        :loading="loading"
        :columns="columns"
        :scroll="{ y: 'calc(100vh - 596px)' }"
        :data="loginLogList"
        :bordered="false"
        :pagination="pagination"
        page-position="br"
        @page-change="handlePageNoChange"
        @page-size-change="handlePageSizeChange"
      >
        <template #status="{ record }">
          <a-tag
            v-if="record.status === 1"
            :color="record.status === 1 ? 'green' : 'red'"
          >
            {{ record.status === 1 ? '成功' : '失败' }}
          </a-tag>
          <a-tooltip v-else :content="record.exception">
            <a-tag
              style="cursor: pointer"
              :color="record.status === 1 ? 'green' : 'red'"
            >
              {{ record.status === 1 ? '成功' : '失败' }}
            </a-tag>
          </a-tooltip>
        </template>
        <template #operation="{ record }">
          <a-popconfirm
            :content="$t('modal.operation.tips')"
            @ok="handleDelete(record.key)"
          >
            <a-button v-permission="'log:operationlog:remove'" type="text"
              >{{ $t('searchTable.operation.remove') }}
            </a-button>
          </a-popconfirm>
        </template>
      </a-table>
    </a-col>
  </a-row>
</template>

<style scoped lang="less"></style>
